package com.baomidou.ant.controller;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.NicelyResynchronizingAjaxController;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 爬虫自动上报
 * @author zbb
 * @date 2021-07-12
 */
@RestController
@Component
@RequestMapping("/htmlunit")
public class HtmlUnit {

    //患者生日，填报时间，发生时间
    private final String birthday = "";
    private final String fillTime = "";
    private final String occurrence = "";


    @RequestMapping("/insert")
    public void contextLoads(){
        try {
            //配置webclient
            WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
            webClient.getOptions().setCssEnabled(false);
            webClient.getOptions().setJavaScriptEnabled(true);
            webClient.getOptions().setTimeout(10000);
            webClient.setJavaScriptTimeout(10000*3);
            webClient.getOptions().setRedirectEnabled(true);
            webClient.getCookieManager().setCookiesEnabled(true);
            webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
            webClient.getOptions().setThrowExceptionOnScriptError(false);
            webClient.setAjaxController(new NicelyResynchronizingAjaxController());//设置支持AJAX
            webClient.waitForBackgroundJavaScript(600*1000);
//          this.loginBaiDu(webClient);
            //登录
            this.loginAliEmail(webClient);
            //等候
            webClient.waitForBackgroundJavaScript(60000);
            webClient.close();
        }
        catch (Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 测试登入阿里邮箱
     * @param webClient
     * @throws Exception
     */
    public void loginAliEmail(WebClient webClient) throws Exception{
        //获取页面
        HtmlPage page = webClient.getPage("https://qiye.aliyun.com/alimail/auth/login");
        webClient.waitForBackgroundJavaScript(10000);
//   System.out.printf(element);
        //获取页面的TITLE
        HtmlInput username = (HtmlInput)page.getElementById("username");
        HtmlInput password = (HtmlInput)page.getElementById("password");
        //输入用户名密码
        username.click();
        username.type("zhoubb@fpe.com.cn");
        password.click();
        password.type("Zhou0323");

        //登录
        HtmlSubmitInput submitInput =(HtmlSubmitInput) page.getElementById("login_submit_btn"); // xpath方式
        submitInput.click();
        webClient.waitForBackgroundJavaScript(60000);
        //页面提示信息
        System.out.println("======>waiting......:");
        System.out.println(page.asText());
        //等待
        System.out.println(page.getUrl().toString());
        // System.out.println(resultPage.getFrames().get(0).getEnclosingPage().asXml());



        System.out.println("========================<<<<<<<<<<<<  目标页:  >>>>>>>>>>>>>===================");
        //重新指向页面，进入填报页
        //page=webClient.getPage("http://111.202.232.186/ADR/page/adrpage/report/adr_report.jsp?reporttype=0");
        webClient.waitForBackgroundJavaScript(60000);
        //打印页面信息
        System.out.println(page.asXml());
        //插入数据
        System.out.println("填报中..........");
        //this.insert(page,webClient);
//        HtmlElement past= (HtmlElement) page.getByXPath("//ul[@id='ext-gen39']/li").get(5);
//        page=past.click();
//        System.out.println(page.asText());
        //System.out.println(resultPage.getFrames().get(0).getEnclosingPage().asXml());
    }



    /**
     * 测试：数据插入
     * @param page
     */
    private void insert(HtmlPage page,WebClient webClient) throws Exception{
        //报告类型
//        HtmlElement newFlag= (HtmlElement) page.getElementById("CHECK_NEW_FLAG");
//        newFlag.click();
        HtmlElement type= (HtmlElement) page.getByXPath("//input[@name='RADIO_HARM_LEVEL']").get(0);
        type.click();
        //姓名填入
        HtmlElement patienName= (HtmlElement) page.getElementById("TEXT_PATIENT_NAME");
        patienName.click();
        patienName.type("张恭卿");
        //点击  男(☆)
        HtmlElement sex= (HtmlElement) page.getByXPath("//input[@name='RADIO_GENDER_ID']").get(0);
        sex.click();
        //选择民族(☆)
        HtmlSelect selectMZ=(HtmlSelect)page.getElementById("SELECT_NATION");
        HtmlOption optionMz=selectMZ.getOptionByValue("1");
        optionMz.click();
        //生日填入
        HtmlElement birthAge1= (HtmlElement) page.getByXPath("//input[@name='birthAge']").get(0);
        birthAge1.click();
        HtmlElement birthDate= (HtmlElement) page.getElementById("DATE_BIRTH_DATE");
        birthDate.setAttribute("value","2021-03-11");
        //年龄填入
        HtmlElement birthAge2= (HtmlElement) page.getByXPath("//input[@name='birthAge']").get(1);
        birthAge2.click();
        HtmlElement age= (HtmlElement) page.getElementById("TEXT_AGE");
        age.setAttribute("value","1");
        //体重填入
        HtmlElement weight= (HtmlElement) page.getElementById("TEXT_WEIGHT");
        weight.click();
        weight.type("10");
        //联系方式
        HtmlElement patientPhone= (HtmlElement) page.getElementById("TEXT_TELPHONE");
        patientPhone.click();
        patientPhone.type("13978560084");
        //原患疾病
        HtmlElement diseaseCategories= (HtmlElement) page.getElementById("TEXT_OLD_DISEASE_NAME");
        diseaseCategories.setAttribute("value","血小板减少；支气管肺炎");
        //既往不良反应
        HtmlElement past=(HtmlElement) page.getByXPath("//input[@name='RADIO_PREVIOUS_NAME']").get(1);
        past.click();
        //家族不良反应
        HtmlElement family=(HtmlElement) page.getByXPath("//input[@name='RADIO_PREVIOUS_NAME']").get(1);
        family.click();
//        //并用药关闭
//        HtmlImage deleteImage = page.getFirstByXPath("//img[@src='../../../images/delete.gif']");
//        deleteImage.click();
        //怀疑用药填写
        HtmlElement approvalNo= (HtmlElement) page.getElementById("A_TEXT_APPROVAL_NO_0");
        approvalNo.click();
        approvalNo.type("国药准字 H20084127");
        //通用名称填写
        HtmlElement generalName=(HtmlElement)page.getElementById("A_TEXT_GENERAL_NAME_0");
        generalName.click();
        generalName.type("注射用乳糖酸阿奇霉素");
        //剂型选择 (☆)
        HtmlSelect selectType=(HtmlSelect)page.getElementById("A_SELECT_DOSAGE_FORM");
        HtmlOption optionType=selectType.getOptionByValue("29");
        optionType.click();
        //生产厂家填入
        HtmlElement factoryName= (HtmlElement) page.getElementById("A_TEXT_FACTORY_NAME_0");
        factoryName.click();
        factoryName.type("大同五洲通有限责任公司");
        //生产批号填入
        HtmlElement batchNo= (HtmlElement) page.getElementById("A_TEXT_BATCH_NO_0");
        batchNo.click();
        batchNo.type("20210301");
        //用量填入(☆)
        HtmlElement drugUnit= (HtmlElement) page.getElementById("A_TEXT_DRUG_UNIT");
        drugUnit.click();
        drugUnit.type("0.1");
        HtmlSelect selectUnit=(HtmlSelect)page.getElementById("A_SELECT_DRUG_UNIT");
        HtmlOption optionUnit=selectUnit.getOptionByValue("4");
        optionUnit.click();
        HtmlElement periodDay= (HtmlElement) page.getElementById("A_TEXT_PERIOD_DAY");
        periodDay.click();
        periodDay.type("1");
        HtmlElement times= (HtmlElement) page.getElementById("A_TEXT_TIMES");
        times.click();
        times.type("1");
        //用药途径(☆)
        HtmlSelect usageMode=(HtmlSelect)page.getElementById("A_SELECT_USAGE_MODE");
        HtmlOption optionMode=usageMode.getOptionByValue("24");
        optionMode.click();
        //用药起止时间
        HtmlElement startDate= (HtmlElement) page.getElementById("A_DATE_START_DATE");
        startDate.setAttribute("value","2021-06-22");
        HtmlElement endDate= (HtmlElement) page.getElementById("A_DATE_END_DATE");
        endDate.setAttribute("value","2021-06-22");
        //用药原因
        HtmlElement cause= (HtmlElement) page.getElementById("A_TEXT_CAUSE_0");
        cause.click();
        cause.type("支原体感染");
        //不良事件反应名称
        HtmlElement adrName= (HtmlElement) page.getElementById("TEXT_ADR_NAME");
        adrName.setAttribute("value","呕吐(一般)");
        //不良事件发生时间
        HtmlElement adrDate= (HtmlElement) page.getElementById("DATETIME_ADR_DATE");
        adrDate.setAttribute("value","2021-06-22");
        //不良事件发生过程
        HtmlElement adrDescribe= (HtmlElement) page.getElementById("TEXTAREA_ADR_DESCRIBE");
        adrDescribe.click();
        adrDescribe.type("2021.06.21门诊拟“血小板减少”将患者收入住院，查体，支原体抗体阳性。使用阿奇霉素治疗后患者呕吐胃内容物。停药后无呕吐.");
        //不良反应的结果
        HtmlElement adrResult= (HtmlElement) page.getByXPath("//input[@name='RADIO_ADR_RESULT']").get(1);
        adrResult.click();
        //停止后是否减轻
        HtmlElement ceaseResult= (HtmlElement) page.getByXPath("//input[@name='RADIO_CEASE_DRUG_RESULT']").get(0);
        ceaseResult.click();
        //再次用药是否有反应
        HtmlElement againResult= (HtmlElement) page.getByXPath("//input[@name='RADIO_AGAIN_DRUG_RESULT']").get(2);
        againResult.click();
        //对原患疾病的影响
        HtmlElement reflectOld= (HtmlElement) page.getByXPath("//input[@name='RADIO_REFLECT_OLD_DISEASE']").get(0);
        reflectOld.click();
        //报告人评价
        HtmlElement reporter= (HtmlElement) page.getByXPath("//input[@name='RADIO_REPORTER']").get(1);
        reporter.click();
        //报告人签字
        HtmlElement evalSign= (HtmlElement) page.getElementById("TEXT_PICKER_EVAL_SIGN");
        evalSign.click();
        evalSign.type("刘慧庆");
        //报告单位
        HtmlElement reportUnit= (HtmlElement) page.getByXPath("//input[@name='RADIO_REPORT_UNIT']").get(1);
        reportUnit.click();
        //报告单位签字
        HtmlElement unitSign= (HtmlElement) page.getElementById("TEXT_RPT_UNIT_SIGN");
        unitSign.click();
        unitSign.type("郭鹏辉");
        //报告人联系电话
        HtmlElement pickerTel= (HtmlElement) page.getElementById("TEXT_PICKER_TEL");
        pickerTel.click();
        pickerTel.type("18720997495");
        //报告人职业(☆)
        HtmlElement job= (HtmlElement) page.getByXPath("//input[@name='RADIO_REPORT_JOB']").get(0);
        job.click();
        //报告人电子邮件
        HtmlElement email= (HtmlElement) page.getElementById("TEXT_PICKER_EMAIL");
        email.click();
        //报告人签名
        HtmlElement pickerSign= (HtmlElement) page.getElementById("TEXT_PICKER_SIGN");
        pickerSign.click();
        pickerSign.type("刘慧庆");
        //报告日期
        HtmlElement reportDate= (HtmlElement) page.getElementById("DATE_REPORT_DATE");
        reportDate.setAttribute("value","2021-07-29");

        //提交按钮
        HtmlInput submit= (HtmlInput) page.getElementById("BUT_TEMPORAEY");
        submit.click();
        webClient.waitForBackgroundJavaScript(10000);
        //跳转页打印
        System.out.println("上传成功:");
        System.out.println(page.asXml());

        //回到首页
    }

    /**
     * 数据填入方法
     * @param page
     * @param entity
     * @throws Exception
     */
//     void insertContent(HtmlPage page, MedicalReportDrug entity) throws Exception{
//        Thread.sleep(20000);
//        //日期数据转化
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//        List<String> ageString = null;
//        if (entity.getBirthday() != null) {
//            birthday = format.format(entity.getBirthday());
//            ageString = CalAge.calAge(birthday);
//            //年龄or出生日期填入
//            HtmlElement birthAge1= (HtmlElement) page.getByXPath("//input[@name='birthAge']").get(0);
//            birthAge1.click();
//            HtmlElement birthDate= (HtmlElement) page.getElementById("DATE_BIRTH_DATE");
//            birthDate.setAttribute("value",birthday);
//        }
//        if (entity.getFillTime() != null) {
//            fillTime = format.format(entity.getFillTime());
//            //填报日期填入
//            HtmlElement fillT= (HtmlElement) page.getElementById("DATE_REPORT_DATE");
//            fillT.setAttribute("value",fillTime);
//        }
//        if (entity.getDateOccurrence() != null) {
//            occurrence = format.format(entity.getDateOccurrence());
//            //事件发生日期填入----先转字符串
//            HtmlElement dateOccurrence= (HtmlElement) page.getElementById("DATETIME_ADR_DATE");
//            dateOccurrence.setAttribute("value",occurrence);
//        }
//        //年龄填写
//        //报告类型
//        HtmlElement newFlag= (HtmlElement) page.getElementById("CHECK_NEW_FLAG");
//        newFlag.click();
//
////        List<HtmlListItem> typeList= page.getByXPath("//label[@id='label_REPORT_TYPE']/input");
//        //不良事件名称
//         //不良事件名称
//         if(entity.getAdverseEventName()!=null){
//             page.getElementById("TEXT_ADR_NAME").setAttribute("value",entity.getAdverseEventName());
//         }else
//             page.getElementById("TEXT_ADR_NAME").setAttribute("value","不详");
//
//        //患者姓名填人
//        HtmlElement patienName= (HtmlElement) page.getElementById("TEXT_PATIENT_NAME");
//        patienName.click();
//        if(entity.getPatienName()!=null) {
//            patienName.type(entity.getPatienName());
//        }
//        //性别填入
//        if(entity.getSex()==null){
//            //点击  不详
//            HtmlElement sex= (HtmlElement) page.getByXPath("//input[@name='RADIO_GENDER_ID']").get(2);
//            sex.click();
//        }else if(Objects.equals(entity.getSex(), "y")){
//            //点击  男
//            HtmlElement sex= (HtmlElement) page.getByXPath("//input[@name='RADIO_GENDER_ID']").get(0);
//            sex.click();
//        }else if(Objects.equals(entity.getSex(), "x")){
//            //点击  女
//            HtmlElement sex= (HtmlElement) page.getByXPath("//input[@name='RADIO_GENDER_ID']").get(1);
//            sex.click();
//            System.out.println(sex.asXml());
//        }
//
//        //原患疾病填入
//        HtmlElement diseaseCategories= (HtmlElement) page.getElementById("TEXT_OLD_DISEASE_NAME");
//        diseaseCategories.setAttribute("value",entity.getDiseaseCategories());
////        HtmlSelect diseaseSelect=(HtmlSelect)page.getByXPath("//input[@name='diseaseCategories']").get(0);
////        HtmlOption options=diseaseSelect.getOption(1);
//        //病案号填入
//        HtmlElement caseId= (HtmlElement) page.getElementById("TEXT_PICKER_EVAL_SIGN");
//        caseId.click();
//        if(entity.getCaseid()!=null) {
//            caseId.type(entity.getCaseid());
//        }
//
//        //事件经过填入
//        HtmlTextArea incident= (HtmlTextArea) page.getElementById("TEXTAREA_ADR_DESCRIBE");
//        incident.click();
//        if(entity.getInvolveNumber()!=null){
//            incident.type(entity.getIncident());
//        }
//
//        //报告人电话
//        HtmlElement reporterPhone= (HtmlElement) page.getElementById("TEXT_PICKER_TEL");
//        reporterPhone.click();
//        if(entity.getReporterPhone()!=null) {
//            reporterPhone.type(entity.getReporterPhone());
//        }
//        //报告人邮箱
//        HtmlElement reporterEmail= (HtmlElement) page.getElementById("TEXT_PICKER_EMAIL");
//        reporterEmail.click();
//        if(entity.getReporterEmail()!=null){
//            reporterEmail.type(entity.getReporterEmail());
//        }
//        //报告人职业
//        if(Objects.equals(entity.getReporterJob(), "医师")){
//            HtmlElement job= (HtmlElement) page.getByXPath("//input[@name='RADIO_REPORT_JOB']").get(0);
//            job.click();
//        }else if(Objects.equals(entity.getReporterJob(), "药剂人员")){
//            HtmlElement job= (HtmlElement) page.getByXPath("//input[@name='RADIO_REPORT_JOB']").get(1);
//            job.click();
//        }else if(Objects.equals(entity.getReporterJob(), "护士") || Objects.equals(entity.getReporterJob(), "护士长")){
//            HtmlElement job= (HtmlElement) page.getByXPath("//input[@name='RADIO_REPORT_JOB']").get(2);
//            job.click();
//        }else{
//            HtmlElement job= (HtmlElement) page.getByXPath("//input[@name='RADIO_REPORT_JOB']").get(3);
//            job.click();
//        }
//
//        Thread.sleep(20000);
//        //提交按钮
//        HtmlButton submit= (HtmlButton) page.getElementById("BUT_SUBMIT");
//        //获取跳转页
//        HtmlPage resPage=submit.click();
//        //跳转页打印
//        System.out.println(resPage.asXml());
//        Thread.sleep(20000);
//    }



}
